//
//  Anniversary.swift
//  BirthdayManager
//
//  Created by Saltsweet on 2020/12/18.
//  Copyright © 2020年 Charles. All rights reserved.
//

import Foundation
import UIKit

class dayinfo: NSObject,NSCoding {
    var headimg: UIImage?
    var dayname: String?
    var date: Date?
    
    init(headimg:UIImage?, dayname: String, date: Date) {
        self.headimg = headimg
        self.dayname = dayname
        self.date = date
    }
    
    //持久化修改结果
    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.headimg, forKey: "imgKey")
        aCoder.encode(self.dayname, forKey: "nameKey")
        aCoder.encode(self.date, forKey: "dateKey")
    }
    
    required init?(coder aDecoder: NSCoder) {
        headimg = ((aDecoder.decodeObject(forKey: "imgKey") as? UIImage))
        dayname = (aDecoder.decodeObject(forKey: "nameKey") as? String)!
        date = (aDecoder.decodeObject(forKey: "dateKey") as? Date)!
    }
    
    static let userPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first! + "/daylist.data"//保存位置，返回该app所能处理的路径
}

extension Date {
    init(_ dateString: String) {
        let dateStringFormatter = DateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
        let date = dateStringFormatter.date(from: dateString)!
        self.init(timeInterval:0, since:date)
        
        
    }
    func toString(dateFormat format : String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
        
    }
}

func yearcount(anniversary: Date) -> String {
    let now = Date()
    let calendar = Calendar.current
    let year = calendar.dateComponents([.year], from: anniversary, to: now)
    let count = year.year!
    return String(count)
    
}

func daycount(anniversary: Date) -> String {
    let cal = Calendar.current
    let today = cal.startOfDay(for: Date())
    let daynmonth = cal.dateComponents([.day, .month], from: anniversary)
    let nextanni = cal.nextDate(after: today, matching: daynmonth, matchingPolicy: .nextTimePreservingSmallerComponents)
    let diff = cal.dateComponents([.day], from: today, to: nextanni!)
    return String(diff.day!)
    
    
}
